package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/prometheus/client_golang/prometheus"
	"io/ioutil"
	"net/http"
	"time"
)

type Collector struct {
	Ctx context.Context
}

func (c Collector) Describe(ch chan<- *prometheus.Desc) {
	ch <- prometheus.NewDesc("dummy", "dummy", nil, nil)
}

func (c Collector) Collect(ch chan<- prometheus.Metric) {
	start := time.Now()
	targetMetrics, err := getMetrics()
	if err != nil {
		ch <- prometheus.NewInvalidMetric(prometheus.NewDesc("http_error", "Error scraping target", nil, nil), err)
		return
	}

	for _, targetMetric := range targetMetrics {
		ch <- targetMetric
	}
	ch <- prometheus.MustNewConstMetric(
		prometheus.NewDesc("http_scrape_duration_seconds", "Total HTTP time scrape took (walk and processing).", nil, nil),
		prometheus.GaugeValue,
		time.Since(start).Seconds(),
	)
}

func getMetrics() ([]prometheus.Metric, error) {
	var allMetrics []prometheus.Metric
	onlineTotal, err := remoteReadOnlineTotal()
	if err != nil {
		return allMetrics, err
	}

	onlineTotalMetric, err := prometheus.NewConstMetric(
		prometheus.NewDesc("online_video_total", "online video total metric", []string{}, nil),
		prometheus.GaugeValue,
		float64(onlineTotal),
	)
	allMetrics = append(allMetrics, onlineTotalMetric)

	return allMetrics, nil
}

func remoteReadOnlineTotal() (int, error) {
	url := "http://restful.vms.customer.console.unicloudcdn.cn:8000/vms?Action=QueryOnlineCamera"

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return 0, err
	}

	req.Header.Add("iam-user-id", "d4f90224-b40e-4b3c-bab9-a5f1c9ef7077")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return 0, err
	}
	defer resp.Body.Close()

	responseBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return 0, err
	}

	type OnlineTotal struct {
		OnlineTotal int `json:"onlineTotal"`
	}

	var responseInfo struct {
		Status bool        `json:"status"`
		Code   string      `json:"code"`
		Res    OnlineTotal `json:"res"`
	}

	err = json.Unmarshal(responseBody, &responseInfo)
	if err != nil {
		fmt.Println("Error unmarshal response body:", err)
		return 0, err
	}
	return responseInfo.Res.OnlineTotal, nil
}
